<?php
/**
 * ============================================================================
 * Copyright (c) 2015-2018 贵州大师兄信息技术有限公司 All rights reserved.
 * siteַ: http://www.dsxcms.com
 * ============================================================================
 * @author:     David Song<songdewei@163.com>
 * @version:    v1.0.0
 * ---------------------------------------------
 * Date: 2018/10/26
 * Time: 9:35 AM
 */

namespace App\Library\Mall;


use App\Library\AuthenticatedUser;
use App\Models\Item;
use Illuminate\Http\Request;

trait CartTrait
{
    use AuthenticatedUser;

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function getItemList(){
        $query = Cart::with(['items'=>function($query){
            return $query->where('uid', $this->uid);
        }])->where('uid', $this->uid);

        $items = $this->request->input('items');
        if (is_array($items)) $query = $query->whereIn('itemid', $items);

        $shops = $query->groupBy('shop_id')->get(['id', 'uid', 'shop_id', 'shop_name'])->map(function ($shop){
            $shop->items = $shop->items->map(function ($item){
                $item->thumb = image_url($item->thumb);
                $item->image = image_url($item->image);
                return $item;
            });
            return $shop;
        });

        return ajaxReturn(['items'=>$shops, 'count'=>$shops->count()]);
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function add(Request $request)
    {
        $itemid = $request->input('itemid');
        $quantity = $request->input('quantity');
        if ($itemid && $quantity) {
            $item = $this->user()->cartItems()->where('itemid', $itemid)->first();
            if ($item) {
                $item->increment('quantity', $quantity);
            } else {
                $item = Item::with('shop')->find($itemid);
                $this->user()->cartItems()->create([
                    'shop_id'=>$item->shop->shop_id,
                    'shop_name'=>$item->shop->shop_name,
                    'itemid'=>$item->itemid,
                    'title'=>$item->title,
                    'quantity'=>$quantity,
                    'price'=>$item->price,
                    'thumb'=>$item->thumb,
                    'image'=>$item->image,
                    'sku_id'=>0,
                    'sku_name'=>'',
                ]);
            }
        }
        return ajaxReturn();
    }

    /**
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateQuantity(Request $request)
    {
        $itemid = $request->input('itemid');
        $quantity = $request->input('quantity');
        if ($itemid && $quantity) {
            $this->user()->cartItems()->where('itemid', $itemid)->update(['quantity'=>$quantity]);
        }
        return ajaxReturn();
    }


}
